package com.demo.javamail.util;

import com.demo.javamail.config.MailConfig;
import org.apache.log4j.Logger;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Properties;

public class MailUtil {

    public final static Logger logger = Logger.getLogger(MailUtil.class.getName());

    private static final String HOST = MailConfig.host;
    private static final Integer PORT = MailConfig.port;
    private static final String USERNAME = MailConfig.userName;
    private static final String PASSWORD = MailConfig.passWord;
    private static final String EMAIL_FORM = MailConfig.emailForm;
    private static final String TIMEOUT = MailConfig.timeout;
    private static final String PERSONAL = MailConfig.personal;
    private static JavaMailSenderImpl mailSender = createMailSender();

    /**
     * 邮件发送器
     *
     * @return 配置工具实现
     */
    private static JavaMailSenderImpl createMailSender() {
        JavaMailSenderImpl sender = new JavaMailSenderImpl();
        sender.setHost(HOST);
        sender.setPort(PORT);
        sender.setUsername(USERNAME);
        sender.setPassword(PASSWORD);
        sender.setDefaultEncoding("Utf-8");
        //如下配置缺一不可
        Properties pro = new Properties();
        pro.setProperty("mail.smtp.timeout", TIMEOUT);
        pro.setProperty("mail.smtp.auth", "false");
        //pro.setProperty("mail.smtp.ssl.enable", "true");
        //pro.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

        sender.setJavaMailProperties(pro);
        return sender;
    }

    /**
     * 发送邮件
     *
     * @param to 接受人
     * @param subject 主题
     * @param html 发送内容
     */
    public static boolean sendMail(String to, String subject, String mailTitle,String mailContent,File mailImage)  {
        boolean isSuccess=false;
        try{
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            // 设置utf-8或GBK编码，否则邮件会有乱码
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
            messageHelper.setFrom(EMAIL_FORM, PERSONAL);
            messageHelper.setTo(to);
            messageHelper.setSubject(subject);

            messageHelper.setText("<html><head></head><body><h1>"+mailTitle +"<div>"+mailContent+
                "</div></h1><img src=\"cid:image\"/></body></html>",true);

            FileSystemResource img = new FileSystemResource(mailImage);
            messageHelper.addInline("image",img);
            mailSender.send(mimeMessage);
            isSuccess=true;

        }catch(Throwable e ){
            logger.error(e.getLocalizedMessage());
            System.out.println(e.getLocalizedMessage());
            e.printStackTrace();
        }
        return isSuccess;
    }
}
